package itsm.isperp.module.controller;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.configuration.ConfCi;
import itsm.isperp.module.entity.incident.IcdIncident;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppMenuService;
import itsm.isperp.module.service.app.AppUserService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.workflow.service.BpmProcessRunService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 系统控制器（初次进入系统）
 * 
 * @author lizx
 * @date 2013-1-7
 * @version V1.0
 */
@Controller
@RequestMapping("help")
public class HelpController {
  @Autowired
  protected AppMenuService appMenuService;

  @Autowired
  IcdIncidentService icdIncidentService;

  @RequestMapping(value = { "" })
  public ModelAndView manager(HttpServletRequest req,
      HttpServletResponse response, RedirectAttributes redirectAttributes) {
    ModelAndView mv = new ModelAndView();
    String type=req.getParameter("type");
    if(StringUtils.isNotBlank(type))
      mv.addObject("type", type);
    mv.setViewName("help/manager");
    return mv;
  }

  @RequestMapping(value = { "edit" })
  public ModelAndView edit(HttpServletRequest req,
      HttpServletResponse response, RedirectAttributes redirectAttributes,
      String id) {
    ModelAndView mv = new ModelAndView();
    IcdIncident model = new IcdIncident();
    model = new IcdIncident();
    model.setId(HibernateUUIDGenerator.generate());
    mv.addObject("model", model);
    if (JudgeIsMoblie(req)) {
      mv.setViewName("help/edit");
    } else {
      mv.setViewName("help/pcEdit");
    }

    return mv;
  }

  public boolean JudgeIsMoblie(HttpServletRequest request) {
    boolean isMoblie = false;
    String[] mobileAgents = { "iphone", "android", "phone", "mobile", "wap",
        "netfront", "java", "opera mobi", "opera mini", "ucweb", "windows ce",
        "symbian", "series", "webos", "sony", "blackberry", "dopod", "nokia",
        "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc",
        "motorola", "foma", "docomo", "up.browser", "up.link", "blazer",
        "helio", "hosin", "huawei", "novarra", "coolpad", "webos", "techfaith",
        "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson",
        "philips", "sagem", "wellcom", "bunjalloo", "maui", "smartphone",
        "iemobile", "spice", "bird", "zte-", "longcos", "pantech", "gionee",
        "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct",
        "320x320", "240x320", "176x220", "w3c ", "acs-", "alav", "alca",
        "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell",
        "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java",
        "jigs", "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui",
        "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-",
        "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port",
        "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri",
        "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony", "sph-", "symb",
        "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v", "voda",
        "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda",
        "xda-", "Googlebot-Mobile" };
    if (request.getHeader("User-Agent") != null) {
      for (String mobileAgent : mobileAgents) {
        if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0) {
          isMoblie = true;
          break;
        }
      }
    }
    return isMoblie;
  }
  
  @RequestMapping(value = { "search" })
  public ModelAndView search(IcdIncident model, HttpServletRequest req,
      RedirectAttributes redirectAttributes) throws SQLException {
    
    String name=req.getParameter("name");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    AppUser user=appUserService.findByOpenid(name,"name","id");
    List<Map<String,Object>> list=null;
    if(user!=null)
    {
      String userId=user.getId();
      JqGridRequest request=new JqGridRequest();
      request.addFilterRule("cus_user_id", JqGridFilterRuleOp.eq, userId);
      list=icdIncidentService.findAllDetailByRequest(request).toPage().getContent();
    }
    ModelAndView mv = new ModelAndView();
    mv.addObject("icdList",list);
    return mv;
  }

  @RequestMapping(value = { "save" })
  public ModelAndView save(IcdIncident model, HttpServletRequest req,
      RedirectAttributes redirectAttributes) throws SQLException {

    ModelAndView mv = new ModelAndView();

    String linkmanName = req.getParameter("linkManName");
    String linkmanPhone = req.getParameter("linkManPhone");
    String description = req.getParameter("description");
    
    model.setTitle(description);
    
    String address = req.getParameter("address");
    description+="\n 位置："+address;
    
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    JqGridRequest request=new JqGridRequest();
    String uuid= HibernateUUIDGenerator.generate();
    String userName=linkmanPhone;
    request.setSearchString("name='"+linkmanPhone+"' or (fullname='"+linkmanName+"' and (mobile='"+linkmanPhone+"' or tel='"+linkmanPhone+"'))");
    AppUser user=appUserService.findOneByRequest(request);
    if(user==null)
    {
      AppUser newUser=new AppUser();
      newUser.setId(uuid);
      newUser.setAddress(address);
      newUser.setFullname(linkmanName);
      newUser.setTel(linkmanPhone);
      newUser.setMobile(linkmanPhone);
      newUser.setAreCustomer(true);
      newUser.setName(linkmanPhone);
      newUser.setEnable(true);
      appUserService.saveOrUpdate(newUser);
      user=newUser;
     // newUser.setSchool(school)
    }else
    {
      userName=user.getMobile();
    }
    String uuid2= HibernateUUIDGenerator.generate();

    model.setSource("Web"); 
    model.setId(uuid2);
    model.setCusUserId(user.getId());
    icdIncidentService.saveOrUpdate(model);
    BpmProcessRunService bpmProcessRunService = ContextHolder
        .getSpringBean("bpmProcessRunService");
    bpmProcessRunService.startProcess(userName, "incidentProcess",
        uuid2,"");
    mv.addObject("type", "success");
    mv.setViewName("redirect:/help");
    return mv;
  }
  
  @RequestMapping(value = { "registerEdit" })
  public ModelAndView registerEdit(HttpServletRequest req,
      HttpServletResponse response, RedirectAttributes redirectAttributes,
      String id) {
    ModelAndView mv = new ModelAndView("help/registerEdit");
    return mv;
  }
  
  @RequestMapping(value = { "registerUserEdit" })
  @ResponseBody
  public ResultMessage registerUserEdit(HttpServletRequest req,
      HttpServletResponse response, RedirectAttributes redirectAttributes,
      String id) {
    String fullname=req.getParameter("fullname");
    String mobile=req.getParameter("mobile");
    String address=req.getParameter("address");
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    AppUser user=appUserService.findByOpenid(mobile);
    if(user==null)
    {
      AppUser newUser=new AppUser();
      newUser.setAddress(address);
      newUser.setFullname(fullname);
      newUser.setMobile(mobile);
      newUser.setAreCustomer(true);
      newUser.setName(mobile);
      newUser.setEnable(true);
      newUser.setPassword("WP5Essdoi1Q=");
      appUserService.saveOrUpdate(newUser);
      return ResultMessage.newInstance(true, "ok");
    }else
    {
      return ResultMessage.newInstance(false, "失败，该手机已注册！");
    }

  }

}
